import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

import { DatabaseConfig } from './database-config/database-config.service';
import { BaseHttpService } from '../base-http.service';

export interface ColumnInfo {
  fieldname: string;
  fieldtype: string;
  fieldcomment: string;
}

export interface TableInfo {
  tablename: string;
  tablecomment: string;
  primarykey: string;
  columninfos: ColumnInfo[];
}

export interface GenerateRequest {
  name: string;
  filepath: string;
  tableinfo: TableInfo;
  isgeneratefile: boolean;
  templatefilename: string;
  generatefilename: string;
  configname: string;
  extension: string;
  projectid: number;
}

@Injectable({
  providedIn: 'root'
})
export class GenerateService {
  private readonly apiPrefix: string = 'Generator';
  constructor(private readonly http: BaseHttpService) {}

  /*
   * confirm current config connection is correct
   *
   * @param {DatabaseConfig} databaseConfig
   * @returns {Observable<boolean>}
   *
   * @memberOf GenerateService
   * */
  public confirmConnect(databaseConfig: DatabaseConfig): Observable<boolean> {
    return this.http.post<boolean>(`/${this.apiPrefix}/ConfirmConnection`, databaseConfig);
  }

  /*
   * get the table list of database
   *
   * @param {string} [tableName='']
   * @returns {Observable<TableInfo[]>}
   *
   * @memberOf GenerateService
   * */
  public getTableList(tableName: string = ''): Observable<TableInfo[]> {
    return this.http.get<TableInfo[]>(`/${this.apiPrefix}/GetTableList`, tableName === '' ? {} : { tableName: tableName });
  }

  /*
   * generate code for all.
   *
   * @param {GenerateRequest} generateRequest
   * @returns {Observable<string[]>}
   *
   * @memberOf GenerateService
   * */
  public commonGenerate(generateRequest: GenerateRequest): Observable<string[]> {
    return this.http.post<string[]>(`/${this.apiPrefix}/CommonGenerate`, generateRequest, { showLoading: true });
  }

  /**
   * generate entity
   * @param generateRequest
   * @returns
   */
  public generateEntity(generateRequest: GenerateRequest): Observable<string[]> {
    return this.http.post<string[]>(`/${this.apiPrefix}/GenerateEntity`, generateRequest, { showLoading: true });
  }

  /**
   * get table info which contains primary key
   * @param tableName
   * @returns
   */
  public getTableInfo(tableName: string): Observable<TableInfo[]> {
    return this.http.get(`/${this.apiPrefix}/GetTableInfo`, { tableName: tableName });
  }
}
